package com.yc.io.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

public class EchoServer {

    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws Exception{
        if (args.length != 1) {
            System.err.println("Usage:" + EchoServer.class.getSimpleName() + "<port>");
            return;
        }
        int i = Integer.parseInt(args[0]);
        new EchoServer(i).start();
    }

    public void start() throws Exception{
        final EchoServerHandler echoServerHandler = new EchoServerHandler();
        // 1创建EvenLoopGroup
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            // 2创建ServerBootstrap
            ServerBootstrap b = new ServerBootstrap();
            b.group(group)
                    .channel(NioServerSocketChannel.class) // 3指定NIO传输Channel
                    .localAddress(new InetSocketAddress(port)) // 4使用指定的端口设置套接字地址
                    .childHandler(new ChannelInitializer<SocketChannel>() {  // 5添加一个EchoServerHandler到子Channel的ChannelPipeline
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            // EchoServerHandler被标注为@Shareable，所以我们可以总是使用同样的实例
                            ch.pipeline().addLast(echoServerHandler);
                        }
                    });
            // 6异步绑定服务器调用sync()方法阻塞等待直到绑定完成
            ChannelFuture sync = b.bind().sync();
            // 7获取Channel的CloseFuture，并阻塞当前线程直到完成
            sync.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync(); // 8关闭EventLoopGroup释放所有资源
        }
    }
}
